<template>
  <section class="details-box">
    <div class="content-top">
      <samp class="content-title float-l">{{titleName}}</samp>
    </div>
    <div class="middle">
    <el-form :model="parameter" ref="parameter" :rules="rules" label-width="120px" class="demo-ruleForm" label-position='left'>
      <el-form-item  label="缴费项目类型" prop="skuTypeId">
        <el-select v-model="skuTypeId" style="width:300px" :disabled="isDisabled">
          <el-option v-for="item in skuTypeIdArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="缴费项目名称" prop="name">
        <el-input type="age" v-model="parameter.name" auto-complete="off" style="width: 300px;" placeholder="请输入项目名称，长度不超过20个字" :disabled="isDisabled"></el-input>
      </el-form-item>
      <el-form-item  label="缴费日期" prop="time">
        <el-date-picker type="daterange" placeholder="请选择收费日期" class="input-name" v-model="parameter.time" @change="change"  
        :picker-options="onPickOptions" style="width: 300px;"></el-date-picker>
      </el-form-item>      
      <el-form-item label="选择缴费班级" prop="gradeListText">
        <el-input type="textarea" v-model="parameter.gradeListText" autosize style="width: 300px;" readonly="readonly" v-show='parameter.gradeListText'></el-input>
        <el-button @click="dialogFormVisible = true" class='buttonName' :class="[parameter.gradeListText ? 'buttonTrue' : '' ]">+ 选择缴费班级</el-button>
        <el-button v-show='parameter.gradeListText' type="text" @click="exportStudent" class="export_button">下载导入模板</el-button>
      </el-form-item>
      <el-form-item  label="缴费项目金额(元)" prop="amount" v-if="!isSingle">
        <el-input type="age" v-model="parameter.amount" auto-complete="off" style="width: 300px;" placeholder="小于100000" :disabled="isDisabled"></el-input>
        <div style="display:inline-block" v-if="parameter.classList.length&&!isDerate&&!isSetDerate">
          <span style="display:inline-block;margin-left: 20px">
            <label class="el-button el-button--text" for="file" v-if="!isDisabled">模板导入</label>
            <form>
              <input type="file" style="position:absolute;clip:rect(0 0 0 0);" id="file" :accept="SheetJSFT" @change="parseExcel"  :multiple="false"/>
            </form>
          </span>
          <!-- <el-button type="text" :disabled="parameter.classList.length!=1 || isDisabled" @click="setDerateSingle" v-if="!isDisabled" style="margin-left: 20px">设置单个学生金额</el-button>
          <el-tooltip v-if="!isDisabled"  class="item" effect="dark" content="当缴费项目只选择一个班级时，可对班级内每个学生单独设置缴费金额" placement="right-start">
            <span class="wenhao">?</span> -->
          <!-- </el-tooltip> -->
        </div>
      </el-form-item>
      <el-form-item  label="缴费项目金额" v-if="isSingle&&!isSetDerate">
        <span style="margin-right:10px">自定义缴费表格</span>
        <el-button type="text" @click="derateDialogShow">查看</el-button>
        <el-button type="text" @click="delDerateSingle" :disabled="isDisabled">删除</el-button>
      </el-form-item>
      <el-form-item  label="选择收款渠道" prop="receiptType">
        <el-select v-model="receiptType" style="width:300px" :disabled="isDisabled">
          <el-option v-for="item in getPaymentAccountArr" :key="item.idType" :label="item.name" :value="item.idType"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="分笔支付" prop="installmentNum">
        <el-checkbox v-model="isInstallment" :disabled="isDisabled">允许分笔支付</el-checkbox> 最多可分   
        <el-select v-model="installmentNum" placeholder="请选择" style="width: 130px" :disabled="!isInstallment || isDisabled">
          <el-option
            v-for="item in stagesOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select> 笔支付
      </el-form-item>
      <el-form-item  label="设置提醒">
        <el-checkbox v-model="isStartNotice" :disabled="isDisabled">开始收费时向缴费用户发送通知</el-checkbox>
      </el-form-item>
      <el-form-item  label=""  prop="endNoticeTime">
        <el-checkbox v-model="isEndNotice" :disabled="isDisabled"></el-checkbox> 距离缴费结束
        <el-select v-model="endNoticeTime" placeholder="请选择" style="width: 130px" :disabled="!isEndNotice || isDisabled">
          <el-option
            v-for="item in sendTimeOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select> 天，向未缴费用户发送通知
      </el-form-item>
      <el-form-item  label="说明">
        <el-input type="textarea" v-model="info" style="width: 300px" :rows='5' :maxlength="100"  placeholder="请输入说明(非必填)" :disabled="isDisabled"></el-input>
        <div class="color-g">该信息将在用户缴费页面显示(最多100个字)</div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('parameter')">保存</el-button>
        <el-button style="color:#20a0ff" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" @open="open" v-bind:close-on-click-modal='false' :before-close="handleClose" custom-class="modelClass">
      <span slot="title">选择缴费班级</span>
      <el-tree :data="parameter.gradeList" show-checkbox="" default-expand-all="" node-key="id" :default-checked-keys="parameter.classList" ref="tree" highlight-current :props="defaultProps"></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getCheckedKeys" class='bottom'>保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="derateSingleVisible" v-bind:close-on-click-modal='false' :before-close="beforeClose" custom-class="modelClass2">
      <span slot="title"><el-tag :type="selectTag == item.id ? 'gray' : ''" v-for="(item, index) in allClassTag" :key="index" style="margin-right:5px;cursor:pointer" @click.native="clickTag(item.id)">{{item.tagName}}</el-tag></span>
      <el-table :data="studentSingleList" ref="derateSingleTable" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="sex" label="性别" :formatter="sexFormat"></el-table-column>
        <el-table-column prop="idType" label="证件类型" :formatter="idTypeFormat"></el-table-column>
        <el-table-column prop="cardNo" label="证件号码" width="200px"></el-table-column>
        <el-table-column prop="gradeYear" label="级别"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column label="缴费金额(元)">
          <template slot-scope="scope">
            <el-input  v-model="scope.row.amount" auto-complete="off" placeholder="小于100000" :disabled="isDisabled"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getDerateSingleStudent" class='bottom' :disabled="isDisabled">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="isLoading" v-bind:close-on-click-modal='false' :show-close="false" custom-class="modelClass3">
        <span class="el-icon-loading"></span>
        <div style="color: #457ed8;text-align: center">正在读取...</div>
    </el-dialog>
  </section>
</template>
<script>
import {addProject, updateProject, modifyProject, gradeList, customDiscount, getDiscountList, customInfoReset} from 'api/school/project/index'
import {getPaymentAccount, getpaymentSku, getPayedLists} from 'api/school/payManage/index'
import {getStudentsList} from 'api/school/student/index'
import common from 'src/util/common'
import {getDayInitTime, sexFilter, idTypeFilter} from 'src/filter/index'
import XLSX from 'xlsx'
let fileSaver = require('file-saver')
// let singleClassId = ''
let oldTime = []
const _SheetJSFT = ['xlsx', 'xls'].map(x => { return '.' + x }).join(',')
export default {
  data () {
    var nameCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('缴费项目名称不能为空'))
      } else {
        if (value.length > 20 || value === Infinity) {
          return callback(new Error('输入缴费项目名称，长度不超过20个字'))
        }
        callback()
      }
    }
    var gradeCheck = (rule, value, callback) => {
      if (this.isSingle) {
        callback()
      } else {
        if (!value) {
          return callback(new Error('缴费项目金额不能为空'))
        } else {
          if (!(/^\d+(.\d{1,2})?$/.test(value))) {
            return callback(new Error('输入金额格式不正确,请输入0.01到99999.99之间的数字(最多两位小数)'))
          } else if (Number(value) >= 100000 || Number(value) < 0.01 || value === Infinity) {
            return callback(new Error('输入金额有误,请输入0.01到99999.99之间的数字(最多两位小数)'))
          }
          callback()
        }
      }
    }
    var timeCheck = (rule, value, callback) => {
      if (!value || !value.length) {
        return callback(new Error('请选择日期'))
      }
      callback()
    }
    var gradeListTextCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('缴费班级必填'))
      }
      callback()
    }
    var installmentNumCheck = (rule, value, callback) => {
      if (this.isInstallment && !this.installmentNum) {
        return callback(new Error('请选择分笔支付笔数'))
      }
      callback()
    }
    var endNoticeTimeCheck = (rule, value, callback) => {
      if (this.isEndNotice && !this.endNoticeTime) {
        return callback(new Error('请选择分笔支付笔数'))
      }
      callback()
    }
    var receiptTypeCheck = (rule, value, callback) => {
      if (!this.receiptType) {
        return callback(new Error('请选择收款渠道'))
      }
      callback()
    }
    var skuTypeIdCheck = (rule, value, callback) => {
      if (!this.skuTypeId) {
        return callback(new Error('请选择缴费类型'))
      }
      callback()
    }
    return {
      id: parseInt(common.params('id')),
      rules: {
        name: [{validator: nameCheck, trigger: 'blur'}],
        skuTypeId: [{validator: skuTypeIdCheck, trigger: 'change'}],
        amount: [{validator: gradeCheck, trigger: 'blur'}],
        time: [{validator: timeCheck, trigger: 'change'}],
        gradeListText: [{validator: gradeListTextCheck, trigger: 'blur'}],
        installmentNum: [{validator: installmentNumCheck, trigger: 'change'}],
        endNoticeTime: [{validator: endNoticeTimeCheck, trigger: 'change'}],
        receiptType: [{validator: receiptTypeCheck, trigger: 'change'}]
      },
      dialogFormVisible: false,
      titleName: '新增缴费项目',
      isLength: false,
      isTrue: false,
      onPickOptions: {
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      parameter: {
        gradeList: [],
        gradeListText: '',
        classList: [],
        time: []
      },
      edit: true, // 是否是编辑模式
      isDisabled: false, // 是否禁止修改数据,添加班级除外
      stagesOptions: [2, 3, 4, 5], // 分笔支付的数据
      sendTimeOptions: [1, 2, 3], // 分笔支付的数据
      isInstallment: false, // 是否开启分笔  默认否
      installmentNum: '', // 分笔笔数
      isStartNotice: false, // 是否开启开始付费通知
      isEndNotice: false, // 是否开启结束时付费通知
      endNoticeTime: '', // 结束通知发送时间
      info: '', // 项目描述
      getPaymentAccountArr: [], // 缴费渠道
      receiptType: '', // 缴费渠道 id_type 字符串
      skuTypeId: '', // 缴费项目类型
      skuTypeIdArr: [], // 缴费项目类型
      isDerate: false, // 是否设置了减免项
      studentSingleList: [], // 单个班级的所有学生
      customAmountList: [], // 自定义缴费金额数组
      getCustomList: [], // 编辑情况下从后台获取的自定义列表
      derateSingleVisible: false, // 是否展示单个班级自定义收费
      isSingle: false, // 是否设置了单个班级自定义缴费金额
      isSetDerate: false, // 是否设置了减免项
      SheetJSFT: _SheetJSFT, // 上传的类型
      isLoading: false, // 读取模板信息
      allClassTag: [], // 用户上传的班级名字
      selectTag: '', // 选中的班级名称
      studentAll: {}, // 已选班级的所有学生
      studentAllGet: false, // 是否获取过已选班级的所有学生
      studentAllByClass: {}, // 根据班级排列的所有学生
      highest: '', // 最高价
      lowest: '' // 最低价
    }
  },
  created () {
    this.getPaymentAccount()
    getpaymentSku().then(v => {
      this.skuTypeIdArr = v.data
    })
    if (this.$route.name === 'detailsProject') {
      this.titleName = '编辑缴费项目'
      this.getData()
    } else {
      this.titleName = '新增缴费项目'
      this.edit = false
      this.getGrade([]) // 获取班级列表
    }
  },
  methods: {
    getData () { // 获取项目详情
      modifyProject({id: parseInt(common.params('id'))}).then(res => {
        this.parameter = {
          id: parseInt(common.params('id')),
          name: res.data.name, // 项目名称
          amount: common.div(res.data.amount, 100).toFixed(2),
          startTime: res.data.startTime,
          endTime: res.data.endTime,
          gradeListText: '',
          classList: res.data.classList,
          time: [new Date(res.data.startTime * 1000), new Date(res.data.endTime * 1000)]
        }
        this.highest = res.data.highest
        this.lowest = res.data.lowest
        oldTime = [...this.parameter.time] // 最开始的缴费时间存起来
        this.isInstallment = !!res.data.isInstallment
        this.installmentNum = res.data.installmentNum
        this.isStartNotice = !!res.data.isStartNotice
        this.isEndNotice = !!res.data.isEndNotice
        this.endNoticeTime = res.data.endNoticeTime
        this.info = res.data.info
        this.skuTypeId = res.data.skuTypeId
        this.receiptType = res.data.paymentSettingId ? `${res.data.paymentSettingId}_${res.data.paymentType}` : ''
        if (new Date(res.data.startTime * 1000) <= new Date()) {
          this.isDisabled = true
        }
        this.getGrade(res.data.classList, this.isDisabled) // 获取班级列表
        this.getCustomInfo()
      })
    },
    getPaymentAccount () { // 获取缴费渠道
      getPaymentAccount().then(res => {
        res.data.schoolPaymentList.forEach(v => {
          if (v.name) {
            v.idType = `${v.id}_${v.type}`
            this.getPaymentAccountArr.push(v)
          }
        })
        res.data.merchantPaymentList.forEach(v => {
          if (v.name) {
            v.idType = `${v.id}_${v.type}`
            this.getPaymentAccountArr.push(v)
          }
        })
        if (this.$route.name !== 'detailsProject') {
          this.receiptType = this.getPaymentAccountArr[0].idType
        }
      })
    },
    getGrade (classList, flag) { // 获取班级列表
      gradeList().then(res => {
        this.changeClassList(classList, res.data, flag)
      })
    },
    changeClassList (list, data, flag) { // 选择学校改变时
      this.parameter.gradeListText = ''
      let gradeText = []
      data.forEach((obj) => {
        obj.gradeId = obj.id
        if (obj.id) { // 在树形结构中改变属性吧id变成gradeId
          delete obj.id
        }
        obj.children.forEach((oo) => {
          if (list.indexOf(oo.id) !== -1) {
            gradeText.push(obj.label + ' ' + oo.label)
            if (flag) {
              oo.disabled = true
            }
          }
        })
      })
      this.parameter.gradeListText = gradeText.join(', ')
      this.parameter.gradeList = data
    },
    change () {
      if (this.isDisabled) {
        if (this.parameter.time[0] - oldTime[0]) {
          this.parameter.time = [...oldTime]
          return this.$message({
            type: 'error',
            message: '缴费开始后,缴费开始时间不能修改',
            duration: 3000
          })
        }
        if (this.parameter.time[1] < oldTime[1]) {
          this.parameter.time = [...oldTime]
          return this.$message({
            type: 'error',
            message: '缴费开始后,缴费结束时间不能提前',
            duration: 3000
          })
        }
      }
    },
    open () {
    },
    handleClose () {
      this.dialogFormVisible = false
    },
    getCheckedKeys () { // 选择班级保存时
      let tmp = this.$refs.tree.getCheckedKeys()
      let errText = ''
      let tmp2 = this.parameter.classList.concat(tmp).filter(v => !this.parameter.classList.includes(v) || !tmp.includes(v)).length
      if (this.isSingle && tmp2) { // 单个班级切换为多个班级的时候,必须先删除已填好的单个班级减免
        if (this.isDisabled) {
          errText = '已设置自定义缴费金额,缴费项目开始后,禁止操作班级'
        } else {
          errText = `已设置自定义缴费金额,不可直接操作班级,如要变更班级请删除自定义缴费表格后在更换班级`
        }
        return this.$alert(errText, '提示', {confirmButtonText: '确定'})
      }
      // if (this.isSingle && parseInt(singleClassId) !== parseInt(tmp[0])) { // 单个班级切换为另一个班级的时候,必须先删除已填好的单个班级减免
      //   if (this.isDisabled) {
      //     errText = '已设置单个学生金额,缴费项目开始后,禁止修改班级'
      //   } else {
      //     errText = `请删除自定义缴费表格后在更换班级`
      //   }
      //   return this.$message({
      //     type: 'error',
      //     message: errText
      //   })
      // }
      this.parameter.classList = tmp
      this.changeClassList(tmp, this.parameter.gradeList)
      this.dialogFormVisible = false
      // if (this.parameter.classList.length === 1) {
      //   singleClassId = this.parameter.classList[0]
      // }
    },
    goBack () {
      this.$router.go(-1)
    },
    setDerateSingle () { // 设置单个班级每个学生不同减免
      let obj = this.amountRule(this.parameter.amount)
      if (!obj.type) {
        return this.$message({
          type: 'error',
          message: obj.message
        })
      }
      getStudentsList({
        classId: this.parameter.classList,
        count: 1000,
        page: 1
      }).then(res => {
        res.data.forEach(v => {
          v.amount = this.parameter.amount
        })
        let obj = {}
        obj[this.parameter.classList[0]] = res.data
        this.changeData(obj)
      })
    },
    getDerateSingleStudent () { // 单个班级减免点击保存
      let tmp1 = Object.keys(this.studentAllByClass).map(v => parseInt(v))
      let tmp2 = this.parameter.classList
      let tmp3 = tmp1.concat(tmp2).filter(v => !tmp1.includes(v) || !tmp2.includes(v)).length
      if (tmp3) {
        return this.$alert('自定义缴费表格中班级与所选班级不同,请检查后再次提交', '提示', {confirmButtonText: '确定'})
      }
      let obj = this.ruleCustom()
      if (!obj.flag) {
        this.derateSingleVisible = true
        this.clickTag(obj.classId)
        return this.$alert(`自定义缴费表格中${obj.name}所在行${obj.message}`, '提示', {confirmButtonText: '确定'})
      } else {
        if (this.id) { // 缴费项目存在直接保存
          this.btnCustomAmount(0)
        } else { // 不存在,跟项目一期提交
          this.isSingle = true
          this.derateSingleVisible = false
        }
      }
    },
    delDerateSingle () { // 删除单个班级设置项目金额项
      if (!this.id) {
        this.isSingle = false
        this.studentSingleList = []
        this.studentAllByClass = {}
      } else {
        this.$confirm(`此操作将把每个学生的缴费金额重置为基础缴费金额:${this.parameter.amount}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          customInfoReset({schoolPaymentSkuId: this.id, classIds: this.parameter.classList}).then(v => {
            this.isSingle = false
            this.studentSingleList = []
            this.studentAllByClass = {}
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {})
      }
    },
    beforeClose () {
      this.derateSingleVisible = false
    },
    submitForm (formName) { // 保存
      if (!this.parameter.time[0] || !this.parameter.time[1]) {
        return this.$message({
          type: 'error',
          message: '请选择缴费时间'
        })
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isInstallment && common.mul(this.parameter.amount, 100) < Number(this.installmentNum)) {
            return this.$message({
              type: 'error',
              message: `缴费金额不能低于0.0${this.installmentNum}`
            })
          }
          if (this.isSingle) { // 验证自定义缴费价格
            // for (let i = 0; i < this.customAmountList.length; i++) {
            //   let v = this.customAmountList[i]
            //   if (v.amount !== this.studentSingleList[i].amount) {
            //     flag = false
            //     this.derateSingleVisible = true
            //     this.$alert(`${this.parameter.gradeListText}缴费表格中${v.name}所在行有修改,但未保存!!!`, '提示', {confirmButtonText: '确定'})
            //     break
            //   }
            // }
            let tmp1 = Object.keys(this.studentAllByClass).map(v => parseInt(v))
            let tmp2 = this.parameter.classList
            let tmp3 = tmp1.concat(tmp2).filter(v => !tmp1.includes(v) || !tmp2.includes(v)).length
            if (tmp3) {
              return this.$alert('所选班级与自定义缴费表格中的班级不同,请检查后再次提交', '提示', {confirmButtonText: '确定'})
            }
            let obj = this.ruleCustom()
            if (!obj.flag) {
              this.derateSingleVisible = true
              this.clickTag(obj.classId)
              return this.$alert(`自定义缴费表格中${obj.name}所在行${obj.message}`, '提示', {confirmButtonText: '确定'})
            }
          }
          this.startTime = getDayInitTime(this.parameter.time[0], 1) / 1000
          this.endTime = getDayInitTime(this.parameter.time[1], 2) / 1000
          var dataVal = {
            name: this.parameter.name, // 项目名称
            info: this.info, // 项目描述
            amount: common.mul(this.parameter.amount || 0, 100), // 金额
            startTime: this.startTime, // 开始时间
            endTime: this.endTime, // 结束时间
            classIds: this.parameter.classList, // 班级id数组[1,2,3]
            isInstallment: this.isInstallment + 0, // 是否分笔付
            installmentNum: Number(this.installmentNum), // 分笔次数
            isStartNotice: this.isStartNotice + 0, // 是否开启开始付费通知
            isEndNotice: this.isEndNotice + 0, // 是否开启结束时付费通知
            endNoticeTime: Number(this.endNoticeTime), // 结束通知发送时间
            skuTypeId: Number(this.skuTypeId), // 缴费类型
            paymentSettingId: parseInt(this.receiptType.split('_')[0]), // 缴费渠道id
            paymentType: parseInt(this.receiptType.split('_')[1]) // 缴费渠道type
          }
          if (this.$route.name === 'detailsProject') {
            dataVal.id = this.parameter.id
            updateProject(dataVal).then(res => { // 编辑
              this.$message({
                type: 'success',
                message: '编辑成功!',
                duration: 500,
                onClose: () => {
                  this.$router.push({name: 'payProject'})
                }
              })
            })
          } else {
            addProject(dataVal).then(res => { // 添加
              if (!this.id && this.isSingle) {
                this.id = res.data.id
                this.btnCustomAmount(1)
              } else {
                this.$message({
                  type: 'success',
                  message: '添加成功!',
                  duration: 2000,
                  onClose: () => {
                    this.$router.push({name: 'payProject'})
                  }
                })
              }
            })
          }
        }
      })
    },
    sexFormat (row, col, value) { // 性别过滤器
      return sexFilter(value)
    },
    idTypeFormat (row, col, value) {
      return idTypeFilter(value)
    },
    amountRule (value) { // 上传自定义信息校验规则
      if (!value) {
        return {message: '缴费项目金额不能为空', type: false}
      } else if (!(/^\d+(.\d{1,2})?$/.test(value))) {
        return {message: '缴费项目金额格式不正确,请输入0.01到99999.99之间的数字(最多两位小数)', type: false}
      } else if (Number(value) >= 100000 || Number(value) < 0.01 || value === Infinity) {
        return {message: '输入金额有误,请输入0.01到99999.99之间的数字(最多两位小数)', type: false}
      } else {
        return {message: '', type: true}
      }
    },
    btnCustomAmount (v) { // 自定义缴费金额提交
      let obj = []
      Object.keys(this.studentAllByClass).forEach(o => {
        this.studentAllByClass[o].forEach(oo => {
          obj.push({studentId: oo.id, amount: common.mul(oo.amount, 100)})
        })
      })
      customDiscount({
        schoolPaymentSkuId: this.id,
        list: obj
      }).then(res => {
        if (v === 0) {
          this.derateSingleVisible = false
          this.$message({
            type: 'success',
            message: '添加成功!',
            duration: 2000
          })
        } else {
          this.customAmountList = JSON.parse(JSON.stringify(this.studentSingleList))
          this.isSingle = true
          this.derateSingleVisible = false
          this.$message({
            type: 'success',
            message: '保存成功!',
            duration: 2000
          })
          this.$router.push({name: 'payProject'})
        }
      })
    },
    derateDialogShow () { // 查看自定义弹窗
      this.derateSingleVisible = true
    },
    getCustomInfo () { // 获取自定义缴费信息
      getDiscountList({id: this.id}).then(v => { // 是否有减免项
        if (v.data.length) {
          this.isSetDerate = true
        } else if (!this.isEqui(this.lowest, this.highest, common.mul(this.parameter.amount, 100))) {
          getPayedLists({
            count: 1000,
            page: 1,
            schoolPaymentSkuId: this.id,
            payStatus: 0,
            classId: this.parameter.classList
          }).then(v => {
            if (v.data.length) {
              let obj = {}
              this.isSingle = true
              v.data.forEach(vv => {
                vv.amount = (vv.shouldPay / 100).toFixed(2)
                vv.id = vv.schoolStudentId
                if (!obj[vv.classId]) {
                  obj[vv.classId] = []
                }
                obj[vv.classId].push(vv)
              })
              this.changeData(obj, 1)
            }
          })
        }
      })
    },
    isEqui (val1, val2, val3) { // 判断是否相等
      return (val1 === val2) && (val2 === val3) && (val1 === val3)
    },
    exportSinglePay (res) { // 导出表格
      let sex = ['默认', '男', '女', '未知']
      let json = [{A: '姓名', B: '性别', C: '证件号码', D: '级别', E: '班级', F: '缴费项目', G: '缴费金额'}]
      for (let k in res) {
        let stu = {}
        stu['A'] = res[k].name
        stu['B'] = sex[res[k].sex]
        stu['C'] = res[k].cardNo
        stu['D'] = res[k].gradeYear
        stu['E'] = res[k].className
        stu['F'] = '缴费项目名'
        stu['G'] = res[k].shouldPay ? common.div(res[k].shouldPay, 100) : this.parameter.amount
        json.push(stu)
      }
      let wscols = [
        {wpx: 100},
        {wpx: 30},
        {wpx: 180},
        {wpx: 80},
        {wpx: 100},
        {wpx: 100},
        {wpx: 50}
      ]
      let wb = {SheetNames: ['Sheet1'], Sheets: {}, Props: {}}
      /* generate workbook object from table */
      wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(json, {header: ['A', 'B', 'C', 'D', 'E', 'F', 'G'], skipHeader: true})
      wb.Sheets['Sheet1']['!cols'] = wscols

      /* get binary string as output */
      let wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'})
      /* force a download */
      fileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '单个金额.xlsx')
    },
    getStudentAll () { // 获取学生
      if (!this.id) {
        return getStudentsList({
          classId: this.parameter.classList,
          count: 3999,
          page: 1
        })
      } else {
        return getPayedLists({
          count: 3999,
          page: 1,
          schoolPaymentSkuId: this.id,
          payStatus: 0,
          classId: this.parameter.classList
        })
      }
    },
    exportStudent () { // 导出表格
      this.getStudentAll().then(res => {
        this.exportSinglePay(res.data)
        this.studentAllGet = true
        for (let k in res.data) {
          this.studentAll[res.data[k].cardNo] = res.data[k]
        }
      })
    },
    clickTag (tagName) {  // 自定义价格表格中点击tag栏,显示不同班级
      this.selectTag = tagName
      this.studentSingleList = this.studentAllByClass[tagName]
    },
    parseExcel (evt) { // 导入自定义金额数据
      let obj = this.amountRule(this.parameter.amount)
      if (!obj.type) {
        return this.$message({
          type: 'error',
          message: obj.message
        })
      }
      let file
      let files = evt.target.files
      if (!files || files.length === 0) {
        return false
      }
      let type = files[0].name.split('.')[1]
      if (!['xlsx', 'xls'].includes(type)) {
        return this.$message({
          type: 'error',
          message: '必须上传以xlsx或者xls结尾的文件'
        })
      }
      file = files[0]
      let reader = new FileReader()
      reader.onload = e => {
        var binary = ''
        var bytes = new Uint8Array(e.target.result)
        var length = bytes.byteLength
        for (var i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i])
        }
        var wb = XLSX.read(binary, {type: 'binary'})
        let res = {}
        let sheetName = wb.SheetNames[0]
        let result = XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {header: 'A', defval: null})
        if (result.length > 0) {
          if (this.studentAllGet) {
            for (let k in result) {
              if (k === 0) continue
              let student = this.studentAll[result[k]['C']]
              if (!result[k]['G'] || result[k]['G'] < 0) continue
              if (student) {
                student.amount = result[k]['G']
                if (!res[student.classId]) {
                  res[student.classId] = []
                }
                res[student.classId].push(student)
              }
            }
            this.changeData(res)
          } else {
            this.getStudentAll().then(v => {
              this.studentAllGet = true
              for (let k in v.data) {
                this.studentAll[v.data[k].cardNo] = v.data[k]
              }
              for (let k in result) {
                if (k === 0) continue
                let student = this.studentAll[result[k]['C']]
                if (!result[k]['G'] || result[k]['G'] < 0) continue
                if (student) {
                  student.amount = result[k]['G']
                  if (!res[student.classId]) {
                    res[student.classId] = []
                  }
                  res[student.classId].push(student)
                }
              }
              this.changeData(res)
            })
          }
        }

        evt.target.value = ''
      }
      reader.readAsArrayBuffer(file)
    },
    changeData (res, type) { // 根据导入的数据进行过滤
      this.studentAllByClass = res
      let list = Object.keys(res).map(v => parseInt(v))
      if (list.length === 0) return this.$message({ message: '缴费金额不能为空', type: 'warning' })
      this.allClassTag = []
      this.parameter.gradeList.forEach((obj) => {
        obj.children.forEach((oo) => {
          if (list.indexOf(oo.id) !== -1) {
            this.allClassTag.push({id: oo.id, tagName: obj.label + oo.label})
          }
        })
      })
      this.selectTag = this.allClassTag[0].id
      this.clickTag(this.selectTag)
      this.isLoading = false
      this.derateSingleVisible = !type
    },
    ruleCustom () {
      let flag = true
      let tmp = {}
      for (let obj of Object.keys(this.studentAllByClass)) {
        for (let v of this.studentAllByClass[obj]) {
          let ruleObj = this.amountRule(v.amount)
          if (!ruleObj.type) {
            flag = false
            tmp.name = v.name
            tmp.message = ruleObj.message
            tmp.classId = v.classId
            break
          }
        }
      }
      return {flag, ...tmp}
    }
  },
  watch: {
    isInstallment (val) { // 是否开启分笔
      val || (this.installmentNum = '')
    },
    isEndNotice (val) { // 是否开启缴费时间到通知
      val || (this.endNoticeTime = '')
    }
  }
}
</script>
<style lang="less">
  .details-box {height: 100%; padding: 20px 10px;}
  .details-box .float-r{float: right;}
  .details-box .float-l{float: left;}
  .details-box .content-top{ clear: both; border-bottom: 1px solid #e1e1e1; height: 30px;}
  .details-box .middle{padding: 10px 20px;}
  .details-box .content-middle{clear: both;}
  .details-box .item{padding: 16px 0; margin-bottom: 22px; font-size: 14px; color: #48576a;}
  .details-box .name{display: inline-block; text-align: left; padding-right: 12px;}
  .details-box .content-middle .input-name{width: 300px;}
  .details-box .save{margin-top: 60px; width: 200px;}
  .details-box .red{color: red; font-size: 12px;}
  .details-box  .buttonName{position: absolute;top: 2px;height: 34px;}
  .details-box  .buttonTrue{left: 325px;}
  .details-box  .export_button{position: absolute;top: 2px;height: 34px;left: 460px;}
  .details-box  .modelClass {width: 320px;}
  .details-box  .modelClass .el-dialog__header{background-color: #457ed8;padding-bottom: 16px;color: #ffffff;}
  .details-box  .modelClass .el-dialog__headerbtn .el-dialog__close{color: #ffffff;}
  .details-box  .modelClass .dialog-footer{text-align: center;}
  .details-box  .modelClass .el-checkbox{float: right;margin-right: 30px; }
  .details-box  .modelClass .bottom{width: 100px;}
  .details-box  .modelClass .el-dialog__body .el-tree--highlight-current{overflow-y: overlay; max-height: 500px; min-height: 300px;}
  .details-box  .modelClass2 {width: 1200px;}
  .details-box  .modelClass2 .el-dialog__header{background-color: #457ed8;padding-bottom: 16px;color: #ffffff;}
  .details-box  .modelClass2 .el-dialog__headerbtn .el-dialog__close{color: #ffffff;}
  .details-box  .modelClass2 .dialog-footer{text-align: center;}
  .details-box  .modelClass2 .el-checkbox{float: right;margin-right: 30px; }
  .details-box  .modelClass2 .bottom{width: 100px;}
  .details-box  .modelClass2 .el-dialog__body{overflow-y: overlay; max-height: 600px; min-height: 300px;}
  .details-box  .modelClass3 {width: 300px; height:160px;text-align: center}
  .color-g { color: #999;}
  .wenhao {
    display: inline-block;
    height: 20px;
    width: 20px;
    line-height: 20px;
    text-align: center;
    border: 1px solid #ccc;
    border-radius: 50%;
  }
  .el-tooltip.item {
    padding: 0;
  } 
</style>